//
//  ST_BlacklistViewController.swift
//  btvideo
//
//  Created by mac on 2020/7/13.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SwiftyJSON
import SwiftyUserDefaults
import MJRefresh
import NIMSDK
import PINRemoteImage

//MARK: - 黑名单
class ST_BlacklistViewController: ST_BTLightBarViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
         
        
        title_nav_btn.setTitleForAllStates("黑名单")
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight+44, left: 0, bottom: 0, right: 0))
        }
        
        request_data()
    }
    
    fileprivate var currentPage = 0
    
    
    
    
    fileprivate func request_data() {
        
        
        currentPage += 1
        
        JVrequest(PH.blackListApi,parameters: ["page":currentPage,"size":21] ,success: { (json) in
            
            
            //            print("22222----",json)
            
            let data = json["data"]
            
            var count = 0
            
            let list = data.arrayValue.map { (itemJson) -> ST_BTUserinfo in
                
                return  (ST_BTUserinfo.deserialize(from: itemJson.rawString() ?? "") ?? ST_BTUserinfo())
            }
            
            if self.currentPage == 1{
                self.data_array = list
            }else{
                self.data_array += list
            }
            
            count = list.count
            
            self.collectionView.reloadData()
            
            self.load_more_option_style(tableView: self.collectionView, count: count, pageSize: 21) {
                
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.request_data()
                })
            }
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
        
        
    }
    
    fileprivate func remove_from_blacklist_handle(id:String,indexPath:IndexPath){
        
        if NIMSDK.shared().userManager.isUser(inBlackList: id){
           
            NIMSDK.shared().userManager.remove(fromBlackBlackList: id) { (error) in
                
                if let e = error{
                    
                    self.toast(text: e.localizedDescription)
                    
                }else{
                    
                    self.push_remove_msg(id: id, indexPath: indexPath)
                }
                
            }
            
        }else{
            
            self.push_remove_msg(id: id, indexPath: indexPath)
        }
        
    }
    
    fileprivate func push_remove_msg(id:String,indexPath:IndexPath){
        
        JVrequest(PH.removeFromBlackListApi,parameters: ["target_accid":id] ,success: { (json) in
            
            self.data_array.remove(at: indexPath.row)
            
            self.collectionView.performBatchUpdates({
                
                self.collectionView.deleteItems(at:[indexPath])
                
               }, completion:nil)
            
            
        }) { (code, err) in
            
            self.toast(text: err)
        }
        
    }
    
    
    //    MARK: - override Properties
    
    
    fileprivate var empty_image_name = "黑名单_空状态"
    
    fileprivate var empty_string = "把黑恶势力都关进来吧"
    //    MARK: - Properties
    
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 15
        controlLayout.minimumInteritemSpacing = 5
        controlLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 10, right: 0)
        
        controlLayout.itemSize = CGSize.init(width: ScreenWidth, height: BlackListCell.height)
        
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        
        control.register(cellWithClass: BlackListCell.self)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = Color.white
        
        control.alwaysBounceVertical = true
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        
        control.emptyDataSetSource = self
        control.emptyDataSetDelegate = self
        return control
    }()
    
    fileprivate var data_array = [ST_BTUserinfo]()
    
    fileprivate var first = true
}


extension ST_BlacklistViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        
        if first{
            self.first = false
            return false
        }else{
            return true
        }
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        
        let attrString = NSMutableAttributedString(string: empty_string)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        
        return UIImage.init(named: empty_image_name)
    }
    
}

extension ST_BlacklistViewController:UICollectionViewDelegateFlowLayout,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: BlackListCell.self, for: indexPath)
        
        cell.model = data_array[indexPath.row]
        
        cell.removeClosure = { iCell,data in
            
            guard let foundCell = self.collectionView.indexPath(for: iCell),let d = data else{
                return
            }
            
            self.remove_from_blacklist_handle(id: d.accid, indexPath: foundCell)
            
        }
        
        return cell
    }
    
    
    
}



//MARK: - Cell
class BlackListCell: UICollectionViewCell {
    
    static let height = 68/375.0*ScreenWidth
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.contentView.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.width.equalTo(avatar_image_view.snp.height)
            make.top.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-10)
        }
        
        contentView.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(avatar_image_view.snp.right).offset(10)
            make.right.equalToSuperview().offset(-15)
        }
        
        contentView.addSubview(removeBtn)
        removeBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.width.height.equalTo(44)
            make.right.equalToSuperview().offset(-2)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    fileprivate lazy var avatar_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = (BlackListCell.height - 20)/2.0
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium)
        return control
    }()
    
    
    
    fileprivate lazy var removeBtn:UIButton = {
        let control = UIButton()
        control.backgroundColor = .clear
        control.setImage(ST_ImageUtils.imageName("blackList_icon_关闭"), for: UIControl.State.normal)
        control.addTarget(self, action: #selector(removeFromBlacklist), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    var model:ST_BTUserinfo?{
        didSet{
            guard let m = model else { return  }
            
            avatar_image_view.pin_setImage(from: m.avatar.compress_small_image(width: 60*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            content_label.text = m.nickname
        }
    }
    
    var removeClosure:((BlackListCell,ST_BTUserinfo?)->())?
    
}

extension BlackListCell{
    
    @objc fileprivate func removeFromBlacklist(){
        
        removeClosure?(self,model)
    }
}
